package com.boe.csb.core.service.api;

import com.boe.csb.core.common.exception.CSBErrorCode;
import com.boe.csb.core.common.exception.CSBException;
import com.boe.csb.core.common.generator.CriteriaGenerator;
import com.boe.csb.core.common.status.AdminUserRole;
import com.boe.csb.core.common.status.CommonStatus;
import com.boe.csb.core.dao.ApiCategoryCriteria;
import com.boe.csb.core.dao.ApiCategoryMapper;
import com.boe.csb.core.dao.BoeApiInfoCriteria;
import com.boe.csb.core.dao.BoeApiInfoMapper;
import com.boe.csb.core.entity.dto.CsbApiInfo;
import com.boe.csb.core.entity.dto.QueryApiCategory;
import com.boe.csb.core.entity.po.ApiCategory;
import com.boe.csb.core.entity.dto.ApiCategoryDTO;
import com.boe.csb.core.entity.po.BoeApiInfo;
import com.boe.csb.core.entity.po.UserOperateLog;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by tianxiang.ltx on 16/11/19.
 */
@Service("apiCategoryService")
public class ApiCategoryService {


    @Autowired
    private ApiCategoryMapper apiCategoryMapper;
    @Autowired
    private BoeApiInfoMapper boeApiInfoMapper;

    private static final Integer MAX_CATEGORY_COUNT = 7;
    /**
     * 查询一级类目
     */
    public List<ApiCategory> queryAllFirstApiCategory() {
        ApiCategoryCriteria criteria = new ApiCategoryCriteria();
        criteria.createCriteria().andParentIdIsNull().andStatusEqualTo(CommonStatus.NORMAL.getStatus());
        return apiCategoryMapper.selectByExample(criteria);
    }

    /**
     * 查询二级类目所有
     */
    public List<ApiCategoryDTO> queryAllApiCategoryList() {
        List<ApiCategoryDTO> apiCategoryDTOList = new ArrayList<>();
        ApiCategoryCriteria criteria = new ApiCategoryCriteria();
        criteria.createCriteria().andStatusEqualTo(CommonStatus.NORMAL.getStatus());
        apiCategoryMapper.selectByExampleWithRowbounds(criteria, new RowBounds(0, 1));
        List<ApiCategory> allApiCategory = apiCategoryMapper.selectByExample(criteria);
        Map<Long, ApiCategoryDTO> map = new HashMap<>();
        //取出一级类目
        for (ApiCategory apiCategory : allApiCategory) {
            ApiCategoryDTO dto = new ApiCategoryDTO();
            if (apiCategory.getParentId() == null) {
                BeanUtils.copyProperties(apiCategory, dto);
                dto.setApiCategoryList(new ArrayList<ApiCategory>());
                map.put(apiCategory.getId(), dto);
                apiCategoryDTOList.add(dto);
            }
        }
        //取出二级类目
        for (ApiCategory apiCategory : allApiCategory) {
            ApiCategoryDTO dto = map.get(apiCategory.getParentId());
            if (dto != null) {
                dto.getApiCategoryList().add(apiCategory);
            }
        }
        return apiCategoryDTOList;
    }

    /**
     * 新增类目
     */
    public void insertApiCategory(ApiCategory apiCategory) {
        if(apiCategory.getParentId()==null && !insertValid()){
            throw  new CSBException(CSBErrorCode.CATEGORY_ERR,"");
        }
        apiCategory.setStatus(CommonStatus.NORMAL.getStatus());
        apiCategory.setGmtModified(new Date());
        apiCategory.setGmtCreate(new Date());
        apiCategoryMapper.insert(apiCategory);
    }

    public boolean insertValid(){
        ApiCategoryCriteria criteria = new ApiCategoryCriteria();
        criteria.createCriteria().andStatusEqualTo(CommonStatus.NORMAL.getStatus()).andParentIdIsNull();
        return apiCategoryMapper.countByExample(criteria)<MAX_CATEGORY_COUNT;
    }


    /**
     * 查询类目
     */
    public List<ApiCategory> queryApiCategoryList(QueryApiCategory query) {
        query.setStatus(CommonStatus.NORMAL.getStatus());
        ApiCategoryCriteria apiCategory = getCriteria(query);
        return apiCategoryMapper.selectByExample(apiCategory);
    }

    public ApiCategory queryCategoryById(Long id){
        return apiCategoryMapper.selectByPrimaryKey(id);
    }

    /**
     * 更新类目
     */
    public void updateApiCategory(ApiCategory apiCategory) {
        Assert.notNull(apiCategory.getId());
        apiCategory.setGmtModified(new Date());
        apiCategoryMapper.updateByPrimaryKeySelective(apiCategory);
    }


    /**
     * 删除类目
     */
    public boolean deleteApiCategory(Long id, Long parentId) {
        if (parentId == null) {
            ApiCategoryCriteria getSecCategory = new ApiCategoryCriteria();
            getSecCategory.createCriteria().andStatusEqualTo(CommonStatus.NORMAL.getStatus()).andParentIdEqualTo(id);
            long secCount = apiCategoryMapper.countByExample(getSecCategory);
            if (secCount > 0) {
                throw new CSBException(CSBErrorCode.CATEGORY_SEC_EXIST, "");
            }
        } else {
            BoeApiInfoCriteria boeApiInfoCriteria = new BoeApiInfoCriteria();
            boeApiInfoCriteria.createCriteria().andCategoryIdEqualTo(id);
            long apiCount = boeApiInfoMapper.countByExample(boeApiInfoCriteria);
            if(apiCount>0)
                throw new CSBException(CSBErrorCode.CATEGORY_SERVICE_EXIST, "");
        }
        //一级类目
        ApiCategory apiCategory = new ApiCategory();
        apiCategory.setStatus(CommonStatus.DELETE.getStatus());
        ApiCategoryCriteria categoryCriteria = new ApiCategoryCriteria();
        categoryCriteria.createCriteria().andIdEqualTo(id);
        apiCategoryMapper.updateByExampleSelective(apiCategory, categoryCriteria);
        return true;
    }


    /**
     * 生成查询条件
     */
    public ApiCategoryCriteria getCriteria(QueryApiCategory query) {
        ApiCategoryCriteria apiCategoryCriteria = new ApiCategoryCriteria();
        ApiCategoryCriteria.Criteria subCriteria = apiCategoryCriteria.createCriteria();
        new CriteriaGenerator<ApiCategoryCriteria, ApiCategory>().generateInner(subCriteria, query);
        return apiCategoryCriteria;
    }
    
    /**
     * 根据二级目录id生产一级类目
     */
    public Map<String,String> getCatagoryInfo(ApiCategory apiCategory){
    	Long id_1 = apiCategory.getParentId();
    	ApiCategory api = queryCategoryById(id_1);
    	Map<String,String> map = new HashMap<String, String>();
    	map.put("catagoryId", apiCategory.getId().toString());
    	map.put("catagoryName", apiCategory.getName());
    	map.put("parentId", api.getId().toString());
    	map.put("parentName", api.getName());
    	
    	return map;
    } 


}
